package main

import (
	"fmt"
	"github.com/asim/go-micro/plugins/config/encoder/yaml/v3"
	"github.com/asim/go-micro/v3/config"
	"github.com/asim/go-micro/v3/config/reader"
	"github.com/asim/go-micro/v3/config/reader/json"
	"github.com/asim/go-micro/v3/config/source/file"
)

/**
 * 使用配置中心
 */

func main() {
	// new yaml encoder
	enc := yaml.NewEncoder()

	// new config
	c, err := config.NewConfig(
		config.WithReader(
			json.NewReader(
				reader.WithEncoder(enc),
			),
		),
	)
	if err != nil {
		panic(err)
	}

	// 加载配置
	if err := c.Load(
		file.NewSource(
			// 相对于命令执行的目录
			file.WithPath("./config/config.yaml"),
		),
	); err != nil {
		panic(err)
	}

	// 打印配置
	fmt.Println("data: ", c.Map())

	// 映射
	type MySqlConfig struct {
		Host string `json:"host"`
		Port int    `json:"port"`
	}
	var mysqlConfig MySqlConfig

	if err := c.Get("hosts", "database", "master").Scan(&mysqlConfig); err != nil {
		panic(err)
	}
	fmt.Println("read config success: ", mysqlConfig)
}
